<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/11/28/028
 * Time: 11:13
 */

namespace app\api\model;


use app\api\service\Token;

use app\api\model\Member as MemberModel;
use app\api\model\ClothesMoneyBill as ClothesMoneyBillModel;
use think\Db;
use think\Exception;

class Registration extends BaseModel {

    /**
     * 检查今天是否签到
     * @param $member_id
     * @return mixed
     */
    public static function check_registration($member_id) {
        // 检查该用户是否已经签到，虽然前端会做判断，但是还是要以防万一
        $registration_time = strtotime(date('Y-m-d'));
        $check_registration = self::where('create_time', $registration_time)->where('member_id', $member_id)->count();
        return $check_registration;
    }

    /**
     * 签到页面数据
     * @return mixed
     */
    public static function registrationIndexInfo() {
        $uid = Token::getCurrentUid();
        $registration['days'] = self::where('member_id', $uid)->count();
        $member = MemberModel::get(['id' => $uid]);
        $registration['clothes_money'] = $member['clothes_money_recharge'] + $member['clothes_money_donate'];
        $registration['is_registration'] = self::check_registration($uid);
        return $registration;
    }

    /**
     * 签到
     * @return mixed
     * @throws Exception
     */
    public static function saveRegistration() {
        $uid = Token::getCurrentUid();

        Db::startTrans();
        try {
            // 添加签到记录
            $data = ['member_id' => $uid, 'create_time' => strtotime(date('Y-m-d'))];
            self::create($data);

            // 签到成功 赠送衣币
            $integral_data = ['member_id' => $uid, 'money' => 1, 'msg' => '签到赠送'];
            ClothesMoneyBillModel::create($integral_data);

            // 更新用户表
            $member = MemberModel::get(['id' => $uid]);
            $member->setInc('clothes_money_donate', 1);

            MemberBill::add_member_bill($uid, 1, '签到赠送', 7, '', '',  '系统赠送', 2);

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }

        $registration['clothes_money'] = $member['clothes_money_recharge'] + $member['clothes_money_donate'];

        return $registration;
    }

    /**
     * 签到记录列表
     * @return \think\Paginator
     */
    public static function registrationList() {
        $uid = Token::getCurrentUid();

        $member_registration_list = self::where('member_id', '=', $uid)->order('create_time desc')->paginate(15, true);

        return $member_registration_list;
    }
}